<template>
  <div class="box">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <div class="loginBox">
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form :model="loginForm" :rules="rules" ref="ruleFormRef">
            <el-form-item prop="username">
              <el-input
                type="text"
                v-model="loginForm.username"
                prefix-icon="User"
                placeholder="请输入账号"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                type="password"
                v-model="loginForm.password"
                prefix-icon="Lock"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
            <el-button
              :loading="loading"
              style="width: 100%"
              size="default"
              type="primary"
              @click="loginBtn(ruleFormRef)"
            >
              登录
            </el-button>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import useUserStore from '@/stores/modules/user.ts'
import { useRouter } from 'vue-router'
import { getTime } from '@/utils/time.ts'
import { ElNotification, FormInstance, FormRules } from 'element-plus'
// 引入useRouter来使用编程式路由跳转
const router = useRouter()
// 定义账号密码
const loginForm = reactive({ username: 'admin', password: '111111' })
// 引入相关的仓库
const userStore = useUserStore()
// 定义类型
interface RuleForm {
  username: string
  password: string
}
const ruleFormRef = ref()
// 定义登录按钮加载状态
const loading = ref(false)
// 登录按钮事件
const loginBtn = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  loading.value = true
  // element里面自带的方法，如果效验通过，valid存在，则运行登录的事件
  // 否则无法进行登录按钮点击
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 效验通过
      try {
        // 异步请求User仓库里登录事件
        await userStore.login(loginForm)
        // 登录成功跳转到首页
        router.push('/')
        ElNotification({
          type: 'success',
          title: `${getTime()}好`,
          message: '欢迎回来',
          duration: 1000,
        })
        // 取消加载状态
        loading.value = false
      } catch (error) {
        // 取消加载状态
        loading.value = false
        ElNotification({
          type: 'error',
          message: (error as Error).message,
          duration: 1000,
        })
      }
    } else {
      // 效验不通过
      loading.value = false
      console.log('error submit!', fields)
    }
  })
}
const validateUserName = (_rule: any, value: any, callback: any) => {
  console.log(_rule)

  if (value === '') {
    callback(new Error('账号不能为空'))
  } else if (value.length >= 5) {
    // callback表示效验通过可以放行
    callback()
  } else {
    callback(new Error('账号长度至少五位'))
  }
}
const validatePassword = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('账号长度至少五位'))
  }
}
// 规则对象
const rules = reactive<FormRules<RuleForm>>({
  username: [
    // 自定义效验规则
    { validator: validateUserName, trigger: 'change' },
    // { required: true, message: '用户名不能为空', trigger: 'change' },
    // { min: 3, max: 6, message: '账号长度至少3位', trigger: 'change' },
  ],
  password: [
    { validator: validatePassword, trigger: 'change' },
    // { required: true, message: '密码不能为空', trigger: 'change' },
    // { min: 6, max: 10, message: '密码长度至少6位', trigger: 'change' },
  ],
})
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100vh;
  background: url(@/assets/images/background.jpg) no-repeat;
  background-size: cover;
  .loginBox {
    background: url(@/assets/images/login_form.png) no-repeat;
    width: 80%;
    top: 30vh;
    position: relative;
    background-size: cover;
    padding: 40px;
    h1 {
      color: #fff;
      font-size: 40px;
    }
    h2 {
      font-size: 20px;
      color: #fff;
      margin: 20px 0;
    }
  }
}
</style>
